import logging
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from question.utils import get_token_user
from .serializers import *

logger = logging.getLogger('django')


class UserView(GenericAPIView):
    """个人详情"""
    queryset = User.objects.all()
    serializer_class = UserDetailSerializer

    def get(self, request):
        user = get_token_user(request)
        data = self.get_serializer(instance=user).data
        return Response(data)

    def put(self, request):
        user = get_token_user(request)
        data = request.data
        User.objects.filter(id=user.id).update(**data)
        data = self.get_serializer(instance=user).data
        return Response(data)


class ChargePasswordView(APIView):
    """改密码"""
    def put(self, request):
        user = get_token_user(request)
        password = self.request.data.get('password')
        user.set_password(password)
        user.save()
        return Response({'success': True, 'message': 'ok'})


class UserLikeView(APIView):
    """关注用户"""
    def post(self, request, pk):
        user = get_token_user(request)
        user.fans.add(pk)
        return Response({'success': True, 'message': 'ok'})

    def delete(self, request, pk):
        user = get_token_user(request)
        user.fans.remove(pk)
        return Response({'success': True, 'message': 'ok'})


class UserLabelView(APIView):
    """改标签"""
    def put(self, reqeust):
        user = get_token_user(reqeust)
        labels = reqeust.data.get('labels')
        user.labels.set(labels)
        return Response({'success': True, 'message': 'ok'})
